<template>
  <div class="container">
    <div class="app-container">
      <!--组织-->

      <el-tree :data="treeData" :props="{ label: 'name' }" default-expand-all :expand-on-click-node="false">
        <template #default="{ data }">
          <el-row
            :style="{ width: '100%' }"
            type="flex"
            justify="space-between"
          >
            <div>{{ data.name }}</div>

            <el-row
              style="width: 140px;"
              type="flex"
              justify="space-between"
            >
              <span>{{ data.managerName }}</span>

              <el-dropdown
                @command="onOperation($event, data.id)"
              >

                <span class="el-dropdown-link"> 操作
                  <i class="el-icon-arrow-down el-icon--right" />
                </span>

                <el-dropdown-menu slot="dropdown">
                  <!-- 2. 绑定指令属性command -->
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>

              </el-dropdown>

            </el-row>
          </el-row>
        </template></el-tree>

    </div>
    <!-- v-model:  :value  @input -->
    <!-- :xxx.sync:  :xxx  @update:xxx -->

    <!-- 5.1 父传子 -->
    <!-- 2. 导入子组件 注册 使用 -->

    <AddDep ref="addDep" :current-id="currentId" :visible.sync="visible" @refresh="loadData" />
    <!-- <AddDep :visible="visible" @update:visible="visible = $event" /> -->
  </div>
</template>

<script>
import { getDepartmentAPI } from '@/api/department'
import { arrayToTree } from '@/utils'
import { delDepartmentAPI } from '@/api/department'
// 3. 导入子组件
import AddDep from './AddDep.vue'

export default {
  name: 'Department',
  components: {
    AddDep
  },
  data() {
    return {
      visible: false,
      currentId: '', // 存储当前点击的id
      treeData: []
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      const res = await getDepartmentAPI()
      const tree = arrayToTree(res)
      this.treeData = tree
    },
    async onOperation(command, id) {
      if (command === 'add') {
        this.visible = true
        this.currentId = id
      }

      if (command === 'edit') {
        this.visible = true
        await this.$refs.addDep.getDepDetail(id)
      }

      if (command === 'del') {
        // 2. 二次确认
        // 3. 关闭国际化英文
        await this.$confirm('是否确认删除', '温馨提示')
        //
        await delDepartmentAPI(id)
        this.$message.success('删除成功')
        this.loadData()
      }
    }
  }
}
</script>
<style scoped>
/* 3. */
.container {
  padding: 30px 140px;
  background-color: white;
  margin: 20px
}
</style>
